package com.blog1.common.advice;

import com.blog1.pojo.response.Result;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.SneakyThrows;
import lombok.Synchronized;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;


@ControllerAdvice
@Slf4j
@ResponseBody
public class responseAdvice implements ResponseBodyAdvice {
    // 注入ObjectMapper对象
    @Autowired
    private ObjectMapper objectMapper;
    // 判断是否支持该类型
    @Override
    public boolean supports(MethodParameter returnType, Class converterType) {
        return true;
    }

    // 在返回体写入之前进行操作
    @Override
    @SneakyThrows
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        // 如果返回体是String类型，则将其转换为JSON字符串
        if(body instanceof String){
return objectMapper.writeValueAsString(Result.success(body));
        }
        if(body instanceof Result){
            return body;
        }
        return Result.success(body);
    }
}
